/*
 * Copyright 2009 Jamie Gennis
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.gwt.remoteaction.server;

import com.google.code.gwt.remoteaction.client.Action;
import com.google.code.gwt.remoteaction.client.ActionError;
import com.google.code.gwt.remoteaction.client.ActionExecutionService;
import com.google.code.gwt.remoteaction.client.ActionResult;
import com.google.code.gwt.remoteaction.client.ActionRuntimeException;
import com.google.code.gwt.remoteaction.client.ConfigurationException;
import com.google.code.gwt.remoteaction.client.RemoteActionService;
import com.google.gwt.rpc.server.RpcServlet;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import java.lang.reflect.InvocationTargetException;
import org.slf4j.Logger;

/**
 * The implementation of the action execution service.  This service dispatches
 * the list of Action objects to their handlers.
 *
 * @author jgennis
 */
public class ActionExecutionServiceImpl extends RpcServlet
    implements ActionExecutionService {

  final Logger logger;

  final Injector injector;

  @Inject
  public ActionExecutionServiceImpl(@ActionExecutionLogger Logger logger, Injector injector) {
    this.logger = logger;
    this.injector = injector;
  }

  public ActionResult execute(Action action) {
    Class<? extends Action> actionClass = action.getClass();
    RemoteActionService service;
    ActionInvoker invoker;
    ActionResultFactory resultFactory;
    try {
      service = getActionHandlerInstance(RemoteActionService.class, actionClass);
      invoker = getActionHandlerInstance(ActionInvoker.class, actionClass);
      resultFactory = getActionHandlerInstance(ActionResultFactory.class,
          actionClass);
    } catch (com.google.inject.ConfigurationException ex) {
      String msg = "A problem with the server's configuration was encountered while attempting to "
          + "execute the action handler for '" + actionClass.getCanonicalName() + "'.";
      logger.error(msg, ex);
      throw new ConfigurationException(msg + "  Check the server log for details.");
    }
    Object result = null;
    try {
      try {
        result = invoker.invokeAction(service, action);
      } catch (InvocationTargetException ex) {
        Throwable cause = ex.getCause();
        try {
          return resultFactory.createFailureResult(cause);
        } catch (IllegalArgumentException argEx) {
          if (cause instanceof RuntimeException) {
            String msg = "A server-side RuntimeException was thrown while executing the action "
                + "handler for '" + actionClass.getCanonicalName() + "'.";
            logger.error(msg, cause);
            ActionRuntimeException are = new ActionRuntimeException(msg + "  Check the server log "
                + "for details.");
            return resultFactory.createFailureResult(are);
          } else if (cause instanceof Error) {
            String msg = "A server-side Error was thrown while executing the handler for '"
                + actionClass.getCanonicalName() + "'.";
            logger.error(msg, cause);
            ActionError ae = new ActionError(msg + "  Check the server log for details.");
            return resultFactory.createFailureResult(ae);
          } else {
            throw argEx;
          }
        }
      }
      return resultFactory.createSuccessResult(result);
    } catch (Exception ex) {
      throw new RuntimeException("Exception thrown while invoking action " + action.toString(),
          ex);
    }
  }

  protected <T> T getActionHandlerInstance(Class<T> clazz, Class<? extends Action> actionClass) {
    ActionHandler annotation = new ActionHandlerImpl(actionClass);
    Key<T> key = Key.get(clazz, annotation);
    return injector.getInstance(key);
  }
}
